import { generateId } from './storage/dataMigration';
import { getToday } from '../utils/dateUtils';
import { PLAN_TYPES, PLAN_STATUS } from '../utils/constants';

/**
 * 计划业务逻辑服务
 */
class PlanService {
  /**
   * 创建日计划
   */
  createDailyPlan(data) {
    const { title, description, priority, tags, estimatedTime, scheduledFor } = data;
    
    return {
      id: generateId(),
      title: title.trim(),
      description: description?.trim() || '',
      type: PLAN_TYPES.DAILY,
      status: PLAN_STATUS.PENDING,
      priority: priority || 'medium',
      tags: tags || [],
      createdAt: new Date().toISOString(),
      scheduledFor: scheduledFor || getToday(),
      completedAt: null,
      notes: '',
      estimatedTime: estimatedTime || null,
      actualTime: null,
      parentId: null,
      order: Date.now(),
      reminderTime: null,
    };
  }

  /**
   * 创建周计划
   */
  createWeeklyPlan(data) {
    const { weekStart, weekEnd, title, description, tasks } = data;
    
    return {
      id: generateId(),
      weekStart,
      weekEnd,
      title: title || '本周计划',
      description: description || '',
      tasks: tasks || [], // 子任务列表
      summary: '',
      completionRate: 0,
      createdAt: new Date().toISOString(),
    };
  }

  /**
   * 创建月计划
   */
  createMonthlyPlan(data) {
    const { month, title, description, tasks } = data;
    
    return {
      id: generateId(),
      month,
      title: title || '本月计划',
      description: description || '',
      tasks: tasks || [], // 子任务列表
      summary: '',
      completionRate: 0,
      createdAt: new Date().toISOString(),
    };
  }

  /**
   * 创建子任务（用于周计划和月计划）
   */
  createSubTask(data) {
    const { title, description, priority, parentId } = data;
    
    return {
      id: generateId(),
      title: title.trim(),
      description: description?.trim() || '',
      status: PLAN_STATUS.PENDING,
      priority: priority || 'medium',
      parentId: parentId,
      createdAt: new Date().toISOString(),
      completedAt: null,
    };
  }

  /**
   * 更新计划状态
   */
  updatePlanStatus(plan, status) {
    return {
      ...plan,
      status,
      completedAt: status === PLAN_STATUS.COMPLETED 
        ? new Date().toISOString() 
        : plan.completedAt,
    };
  }

  /**
   * 计算完成率
   */
  calculateCompletionRate(plans) {
    if (!plans || plans.length === 0) {
      return 0;
    }
    
    const completedCount = plans.filter(
      plan => plan.status === PLAN_STATUS.COMPLETED
    ).length;
    
    return Math.round((completedCount / plans.length) * 100);
  }

  /**
   * 更新周计划完成率（基于子任务）
   */
  updateWeeklyPlanCompletion(weeklyPlan) {
    if (!weeklyPlan.tasks || weeklyPlan.tasks.length === 0) {
      return {
        ...weeklyPlan,
        completionRate: 0,
      };
    }
    
    return {
      ...weeklyPlan,
      completionRate: this.calculateCompletionRate(weeklyPlan.tasks),
    };
  }

  /**
   * 更新月计划完成率（基于子任务）
   */
  updateMonthlyPlanCompletion(monthlyPlan) {
    if (!monthlyPlan.tasks || monthlyPlan.tasks.length === 0) {
      return {
        ...monthlyPlan,
        completionRate: 0,
      };
    }
    
    return {
      ...monthlyPlan,
      completionRate: this.calculateCompletionRate(monthlyPlan.tasks),
    };
  }

  /**
   * 筛选计划
   */
  filterPlans(plans, filters) {
    let filtered = [...plans];
    
    if (filters.type) {
      filtered = filtered.filter(plan => plan.type === filters.type);
    }
    
    if (filters.status) {
      filtered = filtered.filter(plan => plan.status === filters.status);
    }
    
    if (filters.priority) {
      filtered = filtered.filter(plan => plan.priority === filters.priority);
    }
    
    if (filters.date) {
      filtered = filtered.filter(plan => plan.scheduledFor === filters.date);
    }
    
    if (filters.tags && filters.tags.length > 0) {
      filtered = filtered.filter(plan => 
        plan.tags && plan.tags.some(tag => filters.tags.includes(tag))
      );
    }
    
    return filtered;
  }

  /**
   * 排序计划
   */
  sortPlans(plans, sortBy = 'order') {
    const sorted = [...plans];
    
    switch (sortBy) {
      case 'priority':
        const priorityOrder = { high: 3, medium: 2, low: 1 };
        return sorted.sort((a, b) => 
          (priorityOrder[b.priority] || 0) - (priorityOrder[a.priority] || 0)
        );
      
      case 'date':
        return sorted.sort((a, b) => 
          new Date(a.scheduledFor) - new Date(b.scheduledFor)
        );
      
      case 'created':
        return sorted.sort((a, b) => 
          new Date(b.createdAt) - new Date(a.createdAt)
        );
      
      default:
        return sorted.sort((a, b) => (b.order || 0) - (a.order || 0));
    }
  }
}

export default new PlanService();

